home *** CD-ROM | disk | FTP | other *** search
- Path: cpsc.ucalgary.ca!davidt
- From: davidt@cpsc.ucalgary.ca (David Taylor)
- Newsgroups: comp.lang.c++
- Subject: Re: Unions
- Date: 2 Apr 1996 22:40:24 GMT
- Organization: University of Calgary CPSC
- Message-ID: <4jsaco$1pu@linux.cpsc.ucalgary.ca>
- References: <rossfeld.1.00111D6B@ucla.edu>
- NNTP-Posting-Host: fsj.cpsc.ucalgary.ca
- Keywords: Unions
-
- In article <rossfeld.1.00111D6B@ucla.edu>,
- James E Rossfeld <rossfeld@ucla.edu> wrote:
- >Could someone give me a detailed explanation of what the advantages are to
- >using unions (if any). I'm still a little unfamiliar with how they work.
-
- Job security, higher wages... :-)
-
- But seriously, unions are just like structs except all the data
- elements overlap in memory. They are useful when you have a structure
- or class that has two fields that it never uses together. For
- example, this little class stores either an int or a float:
-
- class number {
- private:
- union {
- int int_val;
- float float_val;
- } val;
-
- ...
-
- };
-
- The benefit of doing this is that the union val will take up
- max (sizeof (int), sizeof (float)) instead of sizeof (int) + sizeof
- (float). The disadvantage is that any time int_val is modified,
- float_val gets trashed, and vice versa.
-
- In many cases, it makes sense to just have a base class, and derive
- new subclasses for the shared stuff. The end result is the same.
-
- --
- Andrew Taylor |email: davidt@cpsc.ucalgary.ca
- |www: http://www.cpsc.ucalgary.ca/~davidt
-